package org.ktx.osr.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.*
import org.ktx.osr.MainActivity
import org.ktx.osr.R
import org.ktx.osr.audio.MediaMerger
import org.ktx.osr.data.*
import org.ktx.osr.upload.FileUploadManager
import org.ktx.osr.widget.ProcessingProgressWidget
import java.io.File
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference

/**
 * 音视频处理服务
 * 负责处理音视频合并、文件上传等任务
 */
class MediaProcessingService : Service() {
    
    companion object {
        const val ACTION_SUBMIT_TASK = "org.ktx.osr.action.SUBMIT_TASK"
        const val ACTION_CANCEL_ALL_TASKS = "org.ktx.osr.action.CANCEL_ALL_TASKS"
        const val EXTRA_VIDEO_FILE = "video_file"
        const val EXTRA_AUDIO_FILE = "audio_file"
        const val EXTRA_OUTPUT_FILE = "output_file"
        const val EXTRA_UPLOAD_CONFIG = "upload_config"
        
        private const val NOTIFICATION_ID = 456
        private const val NOTIFICATION_CHANNEL_ID = "MediaProcessingChannel"
    }
    
    private val taskQueue = ConcurrentLinkedQueue<MediaProcessingTask>()
    private val isProcessing = AtomicBoolean(false)
    private val serviceScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val processingJob = AtomicReference<Job?>(null)
    
    private lateinit var windowManager: WindowManager
    private var progressWidget: ProcessingProgressWidget? = null
    private var mediaMerger: MediaMerger? = null
    private var uploadManager: FileUploadManager? = null
    
    private var uploadConfig: UploadConfig? = null
    
    override fun onCreate() {
        super.onCreate()
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mediaMerger = MediaMerger(this)
        uploadManager = FileUploadManager(this)
        
        createNotificationChannel()
        initializeProgressWidget()
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_SUBMIT_TASK -> {
                handleSubmitTask(intent)
            }
            ACTION_CANCEL_ALL_TASKS -> {
                handleCancelAllTasks()
            }
        }
        return START_STICKY
    }
    
    /**
     * 处理提交任务
     */
    private fun handleSubmitTask(intent: Intent) {
        val videoFilePath = intent.getStringExtra(EXTRA_VIDEO_FILE)
        val audioFilePath = intent.getStringExtra(EXTRA_AUDIO_FILE)
        val outputFilePath = intent.getStringExtra(EXTRA_OUTPUT_FILE)
        val config = intent.getParcelableExtra<UploadConfig>(EXTRA_UPLOAD_CONFIG)
        
        if (videoFilePath == null || outputFilePath == null) {
            android.util.Log.e("MediaProcessing", "缺少必要的文件路径参数")
            return
        }
        
        val videoFile = File(videoFilePath)
        val audioFile = audioFilePath?.let { File(it) }
        val outputFile = File(outputFilePath)
        
        if (!videoFile.exists()) {
            android.util.Log.e("MediaProcessing", "视频文件不存在: $videoFilePath")
            return
        }
        
        if (audioFile != null && !audioFile.exists()) {
            android.util.Log.e("MediaProcessing", "音频文件不存在: $audioFilePath")
            return
        }
        
        // 保存上传配置
        if (config != null) {
            uploadConfig = config
        }
        
        // 创建任务并加入队列
        val task = MediaProcessingTask(
            videoFile = videoFile,
            audioFile = audioFile,
            outputFile = outputFile
        )
        
        taskQueue.offer(task)
        android.util.Log.d("MediaProcessing", "任务已加入队列: ${task.id}")
        
        // 开始处理任务
        startProcessing()
    }
    
    /**
     * 处理取消所有任务
     */
    private fun handleCancelAllTasks() {
        taskQueue.clear()
        processingJob.get()?.cancel()
        isProcessing.set(false)
        hideProgressWidget()
        stopForeground(true)
        stopSelf()
    }
    
    /**
     * 开始处理任务
     */
    private fun startProcessing() {
        if (isProcessing.compareAndSet(false, true)) {
            startForeground(NOTIFICATION_ID, createNotification())
            showProgressWidget()
            
            processingJob.set(serviceScope.launch {
                processTasks()
            })
        }
    }
    
    /**
     * 处理任务队列
     */
    private suspend fun processTasks() {
        var currentTaskIndex = 0
        val totalTasks = taskQueue.size
        
        while (taskQueue.isNotEmpty()) {
            val task = taskQueue.poll() ?: break
            currentTaskIndex++
            
            try {
                // 更新任务状态为处理中
                val processingTask = task.updateStatus(MediaProcessingTask.TaskStatus.PROCESSING)
                
                // 更新进度浮窗
                updateProgressWidget(currentTaskIndex, totalTasks, processingTask)
                
                // 处理音视频合并
                val mergedTask = processMediaTask(processingTask)
                
                // 上传文件（如果配置了上传）
                val finalTask = uploadConfig?.let { config ->
                    uploadTaskFiles(mergedTask, config)
                } ?: mergedTask
                
                android.util.Log.d("MediaProcessing", "任务处理完成: ${finalTask.id}")
                
            } catch (e: Exception) {
                android.util.Log.e("MediaProcessing", "任务处理失败: ${task.id}", e)
                val failedTask = task.setError(e.message ?: "未知错误")
                updateProgressWidget(currentTaskIndex, totalTasks, failedTask)
            }
        }
        
        // 所有任务处理完成
        isProcessing.set(false)
        hideProgressWidget()
        stopForeground(true)
        stopSelf()
    }
    
    /**
     * 处理单个媒体任务
     */
    private suspend fun processMediaTask(task: MediaProcessingTask): MediaProcessingTask {
        return withContext(Dispatchers.IO) {
            try {
                updateProgressWidget(0, 0, task.updateProgress(10))
                
                val mediaMerger = this@MediaProcessingService.mediaMerger
                if (mediaMerger == null) {
                    throw Exception("媒体合并器未初始化")
                }
                
                updateProgressWidget(0, 0, task.updateProgress(30))
                
                // 执行音视频合并
                val success = if (task.audioFile != null && task.audioFile.exists()) {
                    mediaMerger.mergeAudioVideo(task.videoFile, task.audioFile, task.outputFile)
                } else {
                    // 仅视频，直接复制
                    task.videoFile.copyTo(task.outputFile, overwrite = true)
                    true
                }
                
                updateProgressWidget(0, 0, task.updateProgress(80))
                
                if (!success) {
                    throw Exception("音视频合并失败")
                }
                
                updateProgressWidget(0, 0, task.updateProgress(100))
                
                task.updateStatus(MediaProcessingTask.TaskStatus.COMPLETED)
                
            } catch (e: Exception) {
                android.util.Log.e("MediaProcessing", "媒体处理失败", e)
                task.setError(e.message ?: "媒体处理失败")
            }
        }
    }
    
    /**
     * 上传任务文件
     */
    private suspend fun uploadTaskFiles(task: MediaProcessingTask, config: UploadConfig): MediaProcessingTask {
        return withContext(Dispatchers.IO) {
            try {
                val uploadManager = this@MediaProcessingService.uploadManager
                if (uploadManager == null) {
                    android.util.Log.w("MediaProcessing", "上传管理器未初始化")
                    return@withContext task
                }
                
                val filesToUpload = mutableListOf<File>()
                
                // 添加上传文件
                if (config.uploadOriginalFiles) {
                    filesToUpload.add(task.videoFile)
                    task.audioFile?.let { filesToUpload.add(it) }
                }
                
                if (config.uploadProcessedFiles && task.outputFile.exists()) {
                    filesToUpload.add(task.outputFile)
                }
                
                if (filesToUpload.isEmpty()) {
                    return@withContext task.updateStatus(MediaProcessingTask.TaskStatus.COMPLETED)
                }
                
                // 执行上传
                val uploadResults = uploadManager.uploadFiles(filesToUpload, config) { fileIndex, progress ->
                    // 更新上传进度
                    val totalProgress = 80 + (progress * 20 / 100) // 80-100% 用于上传
                    updateProgressWidget(0, 0, task.updateProgress(totalProgress))
                }
                
                // 检查上传结果
                val allSuccess = uploadResults.all { it.success }
                if (allSuccess) {
                    task.updateStatus(MediaProcessingTask.TaskStatus.UPLOADED)
                } else {
                    val errorMessages = uploadResults.filter { !it.success }
                        .mapNotNull { it.errorMessage }
                        .joinToString("; ")
                    task.setError("上传失败: $errorMessages")
                }
                
            } catch (e: Exception) {
                android.util.Log.e("MediaProcessing", "文件上传失败", e)
                task.setError("上传异常: ${e.message}")
            }
        }
    }
    
    /**
     * 初始化进度浮窗
     */
    private fun initializeProgressWidget() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            progressWidget = ProcessingProgressWidget(this)
        }
    }
    
    /**
     * 显示进度浮窗
     */
    private fun showProgressWidget() {
        val widget = progressWidget ?: return
        
        if (widget.parent == null) {
            val params = widget.createLayoutParams()
            try {
                windowManager.addView(widget, params)
                widget.show()
            } catch (e: Exception) {
                android.util.Log.e("MediaProcessing", "显示进度浮窗失败", e)
            }
        }
    }
    
    /**
     * 隐藏进度浮窗
     */
    private fun hideProgressWidget() {
        val widget = progressWidget ?: return
        
        if (widget.parent != null) {
            try {
                windowManager.removeView(widget)
            } catch (e: Exception) {
                android.util.Log.e("MediaProcessing", "隐藏进度浮窗失败", e)
            }
        }
    }
    
    /**
     * 更新进度浮窗
     */
    private fun updateProgressWidget(currentIndex: Int, totalTasks: Int, task: MediaProcessingTask) {
        val widget = progressWidget ?: return
        
        serviceScope.launch(Dispatchers.Main) {
            if (totalTasks > 0) {
                widget.updateTaskInfo(currentIndex, totalTasks, task.getDescription())
            }
            
            when (task.status) {
                MediaProcessingTask.TaskStatus.PROCESSING -> {
                    widget.updateProgress(task.progress, "处理中...")
                }
                MediaProcessingTask.TaskStatus.UPLOADING -> {
                    widget.updateProgress(task.progress, "上传中...")
                }
                MediaProcessingTask.TaskStatus.COMPLETED -> {
                    widget.setCompleted()
                }
                MediaProcessingTask.TaskStatus.FAILED -> {
                    widget.setError(task.errorMessage ?: "处理失败")
                }
                else -> {
                    widget.updateProgress(task.progress)
                }
            }
        }
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIFICATION_CHANNEL_ID,
                "音视频处理服务",
                NotificationManager.IMPORTANCE_LOW
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 创建通知
     */
    private fun createNotification(): Notification {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("音视频处理中")
            .setContentText("正在处理音视频文件...")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        processingJob.get()?.cancel()
        serviceScope.cancel()
        hideProgressWidget()
    }
}
